<?php

namespace app\controller;
use app\model\AdminMenu;
use app\BaseController;
use think\facade\Db;


class Menu extends BaseController {
    // 获取所有菜单
    public function getMenuList()
    {
        // 从数据库中获取所有菜单数据，并按照 order 排序
        $menus = Db::name('admin_menu')
            ->order('order', 'asc')
            ->select()
            ->toArray();

        // 构建菜单树
        $menuTree = $this->buildMenuTree($menus);

        // 按照 code, msg, data 格式返回
        $result = [
            'code' => 0,
            'msg' => '成功',
            'data' => $menuTree
        ];
        return json($result);
    }

    private function buildMenuTree($menus, $parentId = 0)
    {
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu['parent_id'] == $parentId) {
                $menu['children'] = $this->buildMenuTree($menus, $menu['id']);
                $tree[] = $menu;
            }
        }
        return $tree;
    }
}


